package com.mercadoutils.controller;

import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mercadolibre.sdk.MeliException;
import com.mercadoutils.domain.SearchTest;



@Controller
public class SearchController {	
	
	SearchTest s = new SearchTest();
	 @RequestMapping("/search.html")
	    public String handleRequest(Model model) throws IOException, MeliException {
		 	String resp = s.doSearch();
		 	
		 	JsonElement jelement = new JsonParser().parse(resp); 
		    JsonObject  jobject = jelement.getAsJsonObject();
		    JsonArray jarray = jobject.getAsJsonArray("results");
		    jobject = jarray.get(0).getAsJsonObject();
		    
		    String html = "<OL>";
		    for(int i = 0 ; i<50;i++){
		    	jobject = jarray.get(i).getAsJsonObject();
		    	html+="<LI>"+jobject.get("title").toString()+"<b> Precio:</b> "+jobject.get("price").toString();
		    }
		    html+="<OL>";
		    
	        model.addAttribute("message", html);
	        return "search";
	    }

}
